package tx.bj12320.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;

import cn.org.rapid_framework.beanutils.BeanUtils;
import cn.org.rapid_framework.web.scope.Flash;

import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.ModelDriven;

import java.util.*;

import javacommon.base.*;
import javacommon.util.*;

import cn.org.rapid_framework.util.*;
import cn.org.rapid_framework.web.util.*;
import cn.org.rapid_framework.page.*;
import cn.org.rapid_framework.page.impl.*;

import tx.bj12320.model.*;
import tx.bj12320.dao.*;
import tx.bj12320.service.*;
import tx.bj12320.vo.query.*;


public class UserInfoAction extends BaseStruts2Action implements Preparable,ModelDriven{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;

	//forward paths
	protected static final String QUERY_JSP = "/pages/UserInfo/query.jsp";
	protected static final String LIST_JSP= "/pages/UserInfo/list.jsp";
	protected static final String CREATE_JSP = "/pages/UserInfo/create.jsp";
	protected static final String EDIT_JSP = "/pages/UserInfo/edit.jsp";
	protected static final String SHOW_JSP = "/pages/UserInfo/show.jsp";
	//redirect paths,startWith: !
	protected static final String LIST_ACTION = "!/pages/UserInfo/list.do";

	private UserInfoManager userInfoManager;

	private UserInfo userInfo;
	Long id = null;
	private String[] items;

	public void prepare() throws Exception {
		if (isNullOrEmptyString(id)) {
			userInfo = new UserInfo();
		} else {
			userInfo = (UserInfo)userInfoManager.getById(id);
		}
	}

	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写 */
	public void setUserInfoManager(UserInfoManager manager) {
		this.userInfoManager = manager;
	}

	private OrgInfoManager orgInfoManager;
	public void setOrgInfoManager(OrgInfoManager manager) {
		this.orgInfoManager = manager;
	}

	public Object getModel() {
		return userInfo;
	}

	public void setUserInfoId(Long val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}

	/** 执行搜索 */
	public String list() {
		UserInfoQuery query = newQuery(UserInfoQuery.class,DEFAULT_SORT_COLUMNS);

		Page page = userInfoManager.findPage(query);

		List result=page.getResult();
		for (Iterator iterator = result.iterator(); iterator.hasNext();) {
			UserInfo ui = (UserInfo) iterator.next();
			if(ui.getOrgInfo().getOrgLevel()==2){
				ui.setParentOrgInfo(orgInfoManager.getLevel1OrgInfo(ui.getOrgInfo()));
			}
		}
		savePage(page,query);
		return LIST_JSP;
	}
	public String listInDeparment() {
		UserInfoQuery query = newQuery(UserInfoQuery.class,DEFAULT_SORT_COLUMNS);
		query.setOrgInfoId(Long.valueOf(getRequest().getParameter("orgInfoId")));
		Page page = userInfoManager.findPage(query);
		savePage(page,query);
		return LIST_JSP;
	}

	/** 查看对象*/
	public String show() {
		return SHOW_JSP;
	}

	/** 进入新增页面*/
	public String create() {
		return CREATE_JSP;
	}

	private IdentityService identityService;

	public void setIdentityService(IdentityService identityService) {
		this.identityService = identityService;
	}

	private String[] roles;


	public String[] getRoles() {
		return roles;
	}

	public void setRoles(String[] roles) {
		this.roles = roles;
	}

	/** 保存新增对象 */
	public String save() {
		userInfoManager.save(userInfo);

		addUserRoles();


		Flash.current().success(CREATED_SUCCESS); //存放在Flash中的数据,在下一次http请求中仍然可以读取数据,error()用于显示错误消息
		return LIST_ACTION;
	}

	private void addUserRoles() {
		OrgInfo oi=orgInfoManager.getById(userInfo.getOrgInfoId());

		User u=identityService.newUser(userInfo.getUserInfoId()+"");

		if(oi.getOrgLevel()==1){//直接在单位下的用户
			u.setFirstName(userInfo.getOrgInfoId()+"");//单位
		}else{ //在部门下的用户
			OrgInfo p_orgInfo=orgInfoManager.getLevel1OrgInfo(oi);
			u.setFirstName(p_orgInfo.getOrgInfoId()+"");//单位
			u.setLastName(userInfo.getOrgInfoId()+"");//部门
		}

		identityService.saveUser(u);
		for (int i = 0; i < roles.length; i++) {
			identityService.createMembership(u.getId(), roles[i]+"_role");
		}
	}
	private void updateUserRoles() {
		List<Group> lgs=identityService.createGroupQuery().groupMember(userInfo.getUserInfoId()+"").list();
		for (Group group : lgs) {
			identityService.deleteMembership(userInfo.getUserInfoId()+"",group.getId());
		}

		for (int i = 0; i < roles.length; i++) {
			identityService.createMembership(userInfo.getUserInfoId()+"", roles[i]+"_role");
		}
	}

	/**进入更新页面*/
	public String edit() {
		List<Group> lgs=identityService.createGroupQuery().groupMember(userInfo.getUserInfoId()+"").list();
		List<String> ls=new ArrayList<String>();
		for (Group group : lgs) {
			ls.add(group.getId().substring(0, group.getId().indexOf("_role")));
		}
		roles=ls.toArray(new String[ls.size()]);


		return EDIT_JSP;
	}

	/**保存更新对象*/
	public String update() {
		userInfoManager.update(this.userInfo);
		if(identityService.createUserQuery().userId(userInfo.getUserInfoId()+"").singleResult()!=null){
			updateUserRoles();
		}else{
			addUserRoles();
		}


		Flash.current().success(UPDATE_SUCCESS);
		return LIST_ACTION;
	}



	/**删除对象*/
	public String delete() {
		for(int i = 0; i < items.length; i++) {
			Hashtable params = HttpUtils.parseQueryString(items[i]);
			Long id = new Long((String)params.get("userInfoId"));
			userInfoManager.removeById(id);
			identityService.deleteUser(id+"");
		}
		Flash.current().success(DELETE_SUCCESS);
		return LIST_ACTION;
	}

}
